<script>
/**
 * @Author: 焦质晔
 * @Date: 2019-06-20 10:00:00
 * @Last Modified by: 焦质晔
 * @Last Modified time: 2019-06-20 10:00:00
 **/
import axios from '@/api/fetch';
// const fs=require('fs')
// const path=require('path')
// var express=new express()
// const router=express.Router();
const JSZip=require('jszip')
import FileSaver from 'file-saver'
export default {
  name: 'DownloadFile',
  props: {
    actionUrl: {
      type: Array,
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false
    },
    isClassification:{
      type: Boolean,
      default: false
    },
    fileName:{
      type:String,
      default:'压缩文件'
    }
  },
  data() {
    return {
      loading: false
    };
  },
  methods: {
    async clickHandle() {
      let fileName=this.fileName;
      if (!this.actionUrl) return;
      if(this.isClassification){
        let list=[]
        let zip=new JSZip();
        this.actionUrl.map(x=>{
          let folder=zip.folder(x.folderName);
          if(x.fileList&&x.fileList.length>0){
              x.fileList.map(y=>{
                let filename=y.name.substring(0, y.name.lastIndexOf("."))+`--${new Date().getTime()}`+y.name.substring(y.name.lastIndexOf("."))
                let pro=this.getFile(y).then(res=>{
                  folder.file(`${filename}`,res)
                })
                list.push(pro)
            })
          }

        })
        // let folder=zip.folder(fileName);
        // this.actionUrl.map(x=>{
        //   let filename=x.name.substring(0, x.name.lastIndexOf("."))+`${new Date().getTime()}`+x.name.substring(x.name.lastIndexOf("."))

        //   const pro=this.getFile(x).then(res=>{
        //     folder.file(`${filename}`,res)
        //   })
        //   console.log(pro,x)
        //   list.push(pro)
        // })
        // console.log(folder)
        Promise.all(list).then(res=>{
          zip.generateAsync({type:'blob'}).then(function(content){
            FileSaver.saveAs(content,`${fileName}.zip`)
          })
        })
      }else{
        let list=[]
        let zip=new JSZip();
        let folder=zip.folder(fileName);
        this.actionUrl.map(x=>{
          let filename=x.name.substring(0, x.name.lastIndexOf("."))+`${new Date().getTime()}`+x.name.substring(x.name.lastIndexOf("."))

          const pro=this.getFile(x).then(res=>{
            folder.file(`${filename}`,res)
          })
          console.log(pro,x)
          list.push(pro)
        })
        //console.log(folder)
        Promise.all(list).then(res=>{
          zip.generateAsync({type:'blob'}).then(function(content){
            FileSaver.saveAs(content,`${fileName}.zip`)
          })
        })
      }



    },
    getFile(data){
      return new Promise((resolve,reject)=>{
        this.downloadUrlFile(data.url,function(file){
            resolve(file)
          })
      })
    },
    downloadUrlFile(url,cb) {
      url= url.replace(/\\/g, '/');
      let that=this;
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
      xhr.onload = () => {
        if (xhr.status === 200) {
          // 获取文件blob数据并保存
          // that.saveAs(xhr.response, name);

          if(cb){
            cb(new Blob([xhr.response]))
            // FileSaver.saveAs(new Blob([xhr.response]),'1.xlsx')
          }
        }
      };

      xhr.send();
    },
    /**
     * URL方式保存文件到本地
     * @param data 文件的blob数据
     * @param name 文件名
     */
    saveAs(data, name) {
      //console.log(data,new Blob([data]))
      return  new Blob([data]);
    },
    // 获取服务端文件 to blob
    async downLoadByUrl(url, params = {}) {
      return await axios({method:'get', url:url, params:params, responseType: 'blob' });
    },
    // 执行下载动作
    async downloadFile(url, params) {
      return window.open(url)
      const { headers, data } = await this.downLoadByUrl(url, params);
      const contentDisposition = headers['content-disposition'];
      // 获取文件名
      const fileName = contentDisposition ? contentDisposition.split(';')[1].split('filename=')[1] : !this.fileName ? url.slice(url.lastIndexOf('/') + 1) : this.fileName;
      // ie10+
      if (navigator.msSaveBlob) {
        navigator.msSaveBlob(data, decodeURI(fileName));
      } else {
        const downloadUrl = window.URL.createObjectURL(data);
        let a = document.createElement('a');
        a.href = downloadUrl;
        a.download = decodeURI(fileName);
        a.click();
        a = null;
      }
    }
  },
  render() {
    const { $attrs, $slots, loading, disabled } = this;
    const wrapProps = {
      props: {
        loading,
        disabled
      },
      attrs: {
        type: 'primary',
        ...$attrs
      },
      on: {
        click: this.clickHandle
      }
    };
    return <el-button {...wrapProps}>{$slots['default']}</el-button>;
  }
};
</script>
